<?php

namespace app\admin\controller;

use app\admin\model\Role as RoleModal;
use app\admin\validate\Role as RoleValidate;
use app\BaseController;
use think\facade\Request as faRequest;

class Role extends BaseController
{
    protected $middleware = ['Auth'];

    public function allList() {
        $params = faRequest::post(['label']);
        $whereArr = [];
        if(isset($params['roleName']) && $params['roleName']) {
            $whereArr[] = ["roleName", "LIKE", '%'.$params['roleName'].'%'];
        }
        $sql = new RoleModal();
        $list = $sql->where($whereArr)->order('create_at', 'desc')->select();
        $list->hidden(['menu_ids'])->toArray();
        return result()->success($list);
    }

    public function getIds()
    {
        $params = $this->request->post(['id']);
        $sql = new RoleModal();
        $info = $sql->find($params['id']);
        $menu_ids = $info['menu_ids'];
        foreach ($menu_ids as $key => $value) {
            $menu_ids[$key] = intval($value);
        }
        return result()->success($menu_ids);
    }

    public function add() {
        $params = faRequest::post(['roleCode','roleName']);
        $validate = new RoleValidate();
        if (!$validate->scene('add')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        $sql = new RoleModal();
        $sql->save($params);
        return result()->success("添加成功");
    }

    public function edit() {
        $params = faRequest::post(['id', 'roleCode','roleName', 'menu_ids']);
        $validate = new RoleValidate();
        if (!$validate->scene('edit')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        $sql = new RoleModal();
        $info = $sql->find($params['id']);
        $info->save($params);
        return result()->success("修改成功");
    }

    public function del() {
        $params = faRequest::post(['id']);
        $validate = new RoleValidate();
        if (!$validate->scene('del')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        $sql = new RoleModal();
        $sql->destroy($params['id']);
        return result()->success("删除成功");
    }

    public function dels() {
        $params = faRequest::post(['ids']);
        $validate = new RoleValidate();
        if (!$validate->scene('dels')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        $sql = new RoleModal();
        $sql->destroy($params['ids']);
        return result()->success("删除成功");
    }
}